#!/usr/bin/python3
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name:         user_verify
# Description:  
# Author:       牛泽鹏
# Date:         2019/7/17
# -------------------------------------------------------------------------------
from django.shortcuts import redirect
from users.models import UserInfo


class Verify:  # 用于验证
    def __init__(self, session, models):
        self.session = session  # session
        self.models = models  # user模型

    def user_is_verify(self):  # 验证器
        try:
            if self.models.objects.get(id=self.session.get('user_id')).username == self.session.get('user'):
                return True
        except self.models.DoesNotExist:
            return False


def verify_user(func):
    def user_state(request):
        try:
            request.session['user_id'], request.session['user']  # 判断用户session是否存在
        except KeyError:  # 不存在情况下
            pass
        else:  # 存在情况下
            verify_obj = Verify(request.session, UserInfo)  # 创建验证模型
            if verify_obj.user_is_verify():  # 验证
                return func(request)  # 通过，访问函数内容
        if not request.session.get('path'):  # 判断session 是否存在跳转的源头路径
            request.session['path'] = request.path if 'users' not in request.path else '/'  # 构建跳转源路径
        return redirect('users:login')  # 返回登录页面
    return user_state





